import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String[] urls = {"public", "login"};

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        boolean isPass = false;
        for (String url : urls) {
            if (request.getRequestURI().contains(url)) {
                isPass = true;
                break;
            }
        }

        if (isPass) {
            filterChain.doFilter(request, response);
        }else {
            HttpSession session = request.getSession();
            String username = (String) session.getAttribute("username");
            if (username != null) {
                filterChain.doFilter(request, response);
            }else {
                response.sendRedirect("login.html");
            }
        }
    }
}